<template>
    <div class="w750">
        <!-- 购物车 -->
        <div class="cart" v-if="shopList.length || invalidCartItems.length || shopActivityList.length" :class="themes.theme">
            <div class="cart-list">
                <div class="entry-con" style="border-radius: 0 0 12px 12px">
                    <div class="con-box" style="border: none">
                        <div class="flex-1 overflow-h">
                            <sendTo :addrData="addrData" :type="1" @choiceAdd="choiceAdd" @onAddress="onAddress" />
                        </div>

                        <div
                            class="mes-txt pl-1"
                            v-if="shopList || shopActivityList"
                            style="justify-content: flex-end; display: flex; align-items: center"
                        >
                            <span class="entry-name" @click="goRecCenter">去领券</span>
                            <span class="spacer"></span>
                            <span class="entry-name" @click="showEdit = !showEdit">{{ showEdit ? '完成' : '编辑' }}</span>
                        </div>
                    </div>
                </div>
                <div class="cart-con" v-for="(shop, shopActIndex) in shopActivityList" :key="shopActIndex">
                    <!-- 满减 -->
                    <div class="promotion-goods">
                        <div class="promotion-item" @click="showPresents(shopActIndex)">
                            <i class="pro-i" style="color: #fff" :style="{ background: themes.color }">满减</i>
                            <span class="pro-span">{{ shop.hitRuleName }}</span>
                            <div class="check" style="color: #333">
                                查看
                                <img src="@/assets/images/arrow.png" style="" />
                            </div>
                        </div>
                        <SwipeCell :right-width="75" v-for="(good, goodIndex) in shop.hitCartItems" :key="goodIndex" v-if="!good.isFailure">
                            <CellGroup>
                                <div class="pro-mes" :style="goodIndex == 0 ? borderTop : ''">
                                    <em
                                        class="choose"
                                        :class="{ cur: good.checkSts }"
                                        @click.stop="changeBasketSts(good.basketId, good.checkSts, 'on', shopActIndex, goodIndex)"
                                    ></em>
                                    <div class="pro-img" @click.stop="goDoodsDetail(good.prodId)">
                                        <legend-image
                                            :pic="good.pic"
                                            :options="{ w: '180', h: '180' }"
                                            :class="'needsclick'"
                                            :isJD="good.prodSource == 'JD'"
                                        />
                                        <img src="@/assets/images/haitao-small.png" class="haitao" v-if="good.goodsType == 'overseas'" />
                                        <span class="type-tip" v-if="good.supportStore">该商品可自提</span>
                                    </div>
                                    <div class="pro-name">
                                        <a href="javascript:;" class="name">{{ good.prodName }}</a>
                                        <div
                                            class="spec sku-click"
                                            v-if="good.cnProperties"
                                            @click.stop="selectSkus(good.prodId, good.skuId, good.basketCount, good.basketId)"
                                        >
                                            {{ good.cnProperties ? good.cnProperties : '默认规格' }}
                                        </div>
                                        <div v-if="good.joinDiscount" style="font-size: 10px; margin: 8px 0" :style="{ color: themes.color }">
                                            【限时折扣】
                                        </div>
                                        <!-- 现实折扣的商品 -->
                                        <span class="price" :style="{ color: themes.color }" v-if="good.joinDiscount">
                                            &#65509;
                                            <em class="now" :style="{ color: themes.color }" style="font-size: 20px">
                                                {{ Money(good.discountPrice)[0] }}
                                            </em>
                                            .{{ Money(good.discountPrice)[1] }}
                                            <span style="text-decoration: line-through; color: #999; margin-left: 2px">
                                                ￥
                                                <em class="now" style="color: #999; font-size: 12px">{{ Money(good.price)[0] }}</em>
                                                .{{ Money(good.price)[1] }}
                                            </span>
                                        </span>

                                        <span class="price" :style="{ color: themes.color }" v-if="!good.joinDiscount">
                                            &#65509;
                                            <em class="now" :style="{ color: themes.color }">{{ Money(good.price)[0] }}</em>
                                            .{{ Money(good.price)[1] }}
                                        </span>
                                    </div>
                                    <div class="pro-num">
                                        <span
                                            class="br0"
																						:class="{'sub-limit': good.basketCount === 1 || good.basketCount <= good.startSaleAmount }"
                                            @click.stop="numChange(-1, good.basketCount, good.prodId, good.skuId, goodIndex, good.basketId)"
                                        >
                                            -
                                        </span>
                                        <input
                                            type="text"
                                            value="1"
                                            class="num"
                                            v-model.number="good.basketCount"
                                            @click.stop
                                            @blur="
                                                manualChangeCount(good.basketCount, good.prodId, good.skuId, goodIndex, good.stocks, good.basketId)
                                            "
                                        />
                                        <span
                                            class="bl0"
																						:class="{'sub-limit': good.basketCount === good.stocks }"
                                            @click.stop="numChange(1, good.basketCount, good.prodId, good.skuId, goodIndex, good.basketId)"
                                        >
                                            +
                                        </span>
                                    </div>
                                </div>
                            </CellGroup>
                            <span
                                slot="right"
                                class="del-goods"
                                :style="{ background: themes.color }"
                                @click.stop="onClose(good.basketId, good.prodId, good.skuId)"
                            >
                                删除
                            </span>
                        </SwipeCell>
                    </div>
                    <!--/无优惠商品-->
                    <!--满减-->
                    <div class="by-self" v-if="shop.supportStore">
                        如需提交自提订单，请选择
                        <a href="javascript:;" class="btn" @click="goStoreSub(shopIndex)">门店自提</a>
                    </div>
                </div>
                <div class="cart-con">
                    <!-- 无优惠商品 -->
                    <SwipeCell :right-width="75" v-for="(good, goodIndex) in shopList" :key="goodIndex">
                        <CellGroup>
                            <div class="pro-mes" :style="goodIndex == 0 ? borderTop : ''">
                                <em
                                    class="choose"
                                    :class="{ cur: good.checkSts }"
                                    @click.stop="changeBasketSts(good.basketId, good.checkSts, 'none', goodIndex)"
                                ></em>
                                <div class="pro-img" @click.stop="goDoodsDetail(good.prodId)">
                                    <legend-image
                                        :pic="good.pic"
                                        :options="{ w: '180', h: '180' }"
                                        :class="'needsclick'"
                                        :isJD="good.prodSource == 'JD'"
                                    />
                                    <img src="@/assets/images/haitao-small.png" class="haitao" v-if="good.goodsType == 'overseas'" />
                                    <span class="type-tip" v-if="good.supportStore">该商品可自提</span>
                                </div>
                                <div class="pro-name">
                                    <a href="javascript:;" class="name">{{ good.prodName }}</a>
                                    <div
                                        class="spec sku-click"
                                        v-if="good.cnProperties"
                                        @click.stop="selectSkus(good.prodId, good.skuId, good.basketCount, good.basketId)"
                                    >
                                        {{ good.cnProperties ? good.cnProperties : '默认规格' }}
                                    </div>
                                    <div v-if="good.joinDiscount" style="font-size: 10px; margin: 8px 0" :style="{ color: themes.color }">
                                        【限时折扣】
                                    </div>
                                    <span class="price" :style="{ color: themes.color }" v-if="good.joinDiscount">
                                        &#65509;
                                        <em class="now" :style="{ color: themes.color }" style="font-size: 20px">
                                            {{ Money(good.discountPrice)[0] }}
                                        </em>
                                        .{{ Money(good.discountPrice)[1] }}
                                        <span style="text-decoration: line-through; color: #999; margin-left: 2px">
                                            ￥
                                            <em class="now" style="color: #999; font-size: 12px">{{ Money(good.price)[0] }}</em>
                                            .{{ Money(good.price)[1] }}
                                        </span>
                                    </span>

                                    <span class="price" :style="{ color: themes.color }" v-if="!good.joinDiscount">
                                        &#65509;
                                        <em class="now" :style="{ color: themes.color }">{{ Money(good.price)[0] }}</em>
                                        .{{ Money(good.price)[1] }}
                                    </span>

                                    <!-- <span class="price" :style="{'color': themes.color}">&#65509;<em class="now" :style="{'color': themes.color}">{{(good.price + '.00').split('.')[0]}}</em>.{{(good.price + '.00').split('.')[1]}}</span> -->
                                </div>
                                <div class="pro-num">
                                    <span
                                        class="br0"
																				:class="{'sub-limit': good.basketCount === 1 || good.basketCount <= good.startSaleAmount }"
                                        @click.stop="numChange(-1, good.basketCount, good.prodId, good.skuId, goodIndex, good.basketId)"
                                    >
                                        -
                                    </span>
                                    <input
                                        type="text"
                                        value="1"
                                        class="num"
                                        v-model.number="good.basketCount"
                                        @click.stop
                                        @blur="manualChangeCount(good.basketCount, good.prodId, good.skuId, goodIndex, good.stocks, good.basketId)"
                                    />
                                    <span 
																			class="bl0"
																			:class="{'sub-limit':  good.basketCount === good.stocks }"
																			@click.stop="numChange(1, good.basketCount, good.prodId, good.skuId, goodIndex, good.basketId)">
                                        +
                                    </span>
                                </div>
                            </div>
                        </CellGroup>
                        <span
                            slot="right"
                            class="del-goods"
                            :style="{ background: themes.color }"
                            @click.stop="onClose(good.basketId, good.prodId, good.skuId)"
                        >
                            删除
                        </span>
                    </SwipeCell>
                </div>
                <!-- 失效商品 -->
                <div class="cart-con overtime" v-if="invalidCartItems && invalidCartItems.length != 0">
                    <div class="over-tit">失效商品</div>
                    <SwipeCell :right-width="75" v-for="(good, goodIndex) in invalidCartItems" :key="goodIndex">
                        <CellGroup>
                            <div class="pro-mes" :style="goodIndex == 0 ? borderTop : ''">
                                <em class="over-tag">失效</em>
                                <a href="javascript:;" class="pro-img">
                                    <legend-image
                                        :pic="good.pic"
                                        :options="{ w: '180', h: '180' }"
                                        :class="'needsclick'"
                                        :isJD="good.prodSource == 'JD'"
                                    />
                                    <img src="@/assets/images/haitao-small.png" class="haitao" v-if="good.goodsType == 'overseas'" />
                                </a>
                                <div class="pro-name">	
                                    <a href="javascript:;" class="name">{{ good.prodName }}</a>
                                    <span class="over-txt">{{ good.cnProperties }}</span>
                                    <div class="over-btn">
																					<span class="des">该商品无法购买</span>
																					<a href="javascript:;" class="btn" :style="{ 'border-color': themes.color }" @click.stop="reChecked(good.prodId)">
																					    重新选择
																					</a>
                                    </div>
                                </div>
                            </div>
                        </CellGroup>
                        <span slot="right" class="del-goods" @click.stop="onClose(good.basketId, good.prodId, good.skuId)">删除</span>
                    </SwipeCell>
                    <div class="clear-overtime" @click.stop="clearInvalid"><a href="javascript:;" class="clear-btn">清空失效商品</a></div>
                </div>
                <!-- /失效商品 -->
            </div>
            <!-- 选择sku -->
            <div class="popup-hide" :class="{ show: showSkuList }">
                <div class="popup-box">
                    <div class="spec-menu">
                        <!-- 图片、价格 -->
                        <div class="spec-menu-up">
                            <div class="spec-img">
                                <img :src="skuImages ? $imgUrlHead + skuImages : '@/assets/images/default-goods-img.jpg'" alt="" />
                            </div>
                            <i class="close close-pop" @click="closeAll"></i>
                            <div class="spec-name">{{ prodName }}</div>

                            <span class="spec-price" :style="{ color: themes.color }" v-if="joinDiscount">
                                &#65509;
                                <em class="now" :style="{ color: themes.color }" style="font-size: 20px">{{ Money(promotionPrice)[0] }}</em>
                                .{{ Money(promotionPrice)[1] }}
                                <span style="text-decoration: line-through; color: #999; margin-left: 2px">
                                    ￥
                                    <em class="now" style="color: #999; font-size: 12px">
                                        {{ Money(promotionPrice / (discount == 0 ? discount : discount / 10))[0] }}
                                    </em>
                                    .{{ Money(promotionPrice / (discount == 0 ? discount : discount / 10))[1] }}
                                </span>
                            </span>

                            <span class="spec-price" v-else>
                                ￥
                                <em class="price">{{ Money(promotionPrice)[0] }}</em>
                                .{{ Money(promotionPrice)[1] }}
                            </span>
                        </div>
                        <!-- /图片、价格 -->
                        <!-- 规格、属性 -->
                        <div class="spec-menu-middle">
                            <div class="pro-att" v-if="paramData" v-for="(prodProp, prodPropIndex) in paramData" :key="prodPropIndex">
                                <span class="spec-tit">{{ prodProp.key }}</span>
                                <div class="spec-con clearfix">
                                    <div
                                        tag="a"
                                        v-for="(prodPropVal, prodPropValIndex) in prodProp.attrArr"
                                        :key="prodPropValIndex"
                                        class="item"
                                        :class="{
                                            on: prodPropVal.choose == 'on',
                                            unable: prodPropVal.disable == true,
                                            pointerEvents: prodPropVal.disable == true
                                        }"
                                        @click="currentFilter(prodPropValIndex, prodPropIndex, prodProp.key, prodPropVal.value)"
                                    >
                                        {{ prodPropVal.value }}
                                    </div>
                                </div>
                            </div>
                            <div class="pro-num clearfix">
                                <span class="spec-tit">
                                    数量
                                    <span class="stock">（库存：{{ stocks }}）</span>
                                </span>

                                <div class="add-sub">
                                    <a href="javascript:;" class="sub-a sub-limit" @click.stop="changeSpuCount(-1, prodCount)">-</a>
                                    <input type="text" value="1" class="sub-input" v-model="prodCount" />
                                    <a href="javascript:;" class="sub-a" @click.stop="changeSpuCount(1, prodCount)">+</a>
                                </div>
                            </div>
                        </div>
                        <!-- /规格、属性 -->
                        <!-- 按钮 -->
                        <button class="popup-btn" @click.stop="changeSelectedSku">确定</button>
                        <!-- /按钮 -->
                    </div>
                </div>
            </div>
            <!-- /选择sku -->
            <div class="cart-btn" id="cart-btn-1" v-if="!showEdit">
                <div class="cart-btn-box">
                    <div class="left" @click="changeAllShop">
                        <em class="choose" :class="{ cur: allChecked }"></em>
                        全选
                    </div>
                    <div class="mid">
                        <div class="total">
                            总计：
                            <span class="price">{{ Money(result.orderActualTotal)[0] }}.{{ Money(result.orderActualTotal)[1] }}</span>
                        </div>
                        <div class="sale-off">
                            (不含运费，已优惠
                            <span class="discount">{{ Money(result.promotionAmount)[0] }}.{{ Money(result.promotionAmount)[1] }}</span>
                            )
                        </div>
                    </div>
                    <a href="javascript:;" class="right" :class="{ disabled: !checkedGoodsNum || !isPurchase}" @click="settlement">
                        结算&nbsp;(
                        <span class="num">{{ checkedGoodsNum }}</span>
                        )
                    </a>
                    <!-- <a href="#" class="right not-choose">结算&nbsp;(<span class="num">0</span>)</a> -->
                </div>
            </div>
            <!-- 编辑 -->
            <div class="cart-btn" id="cart-btn-2" v-if="showEdit">
                <div class="cart-btn-box">
                    <div class="left" @click="changeAllShop">
                        <em class="choose" :class="{ cur: allChecked }"></em>
                        全选
                    </div>
                    <div class="edit-btn">
                        <!--<a href="javascript:;" class="btn foc" @click.stop="favoriteSomeGoodsDels">添加收藏</a>-->
                        <a
                            href="javascript:;"
                            class="btn"
                            :class="{ del: !checkedGoods }"
                            :style="{ background: checkedGoods ? themes.color : '#ccc' }"
                            @click.stop="deleteShopCarts"
                        >
                            删除已选
                        </a>
                    </div>
                </div>
            </div>
            <!-- /编辑 -->
        </div>
        <div class="empty" v-if="!shopList.length && !invalidCartItems.length && !shopActivityList.length">
            <div class="item-img"><img src="@/assets/images/cart-empty.png" alt="" /></div>
            <div class="item-txt">您的购物车还是空的，赶紧去逛逛吧！</div>
            <div class="item-btn" @click="goIndex()" :style="{ background: themes.color }">去逛逛</div>
            <!-- 版权 -->
            <copyrightInfo />
        </div>
        <!-- /购物车 -->

        <!-- 促销信息 -->
        <div class="popup-hide" :class="{ show: showActivity }">
            <div class="popup-box">
                <div class="popup-tit">
                    <em class="tit">促销信息</em>
                    <i class="close close-pop" @click="closeAll"></i>
                </div>
                <div class="popup-con promotion-msg">
                    <!-- v-for="(item,index) in shopActivityList[presentsIndex]" :key="index" -->
                    <div class="item">
                        <div class="item-tit">
                            <em class="tit-em">1.</em>
                            <template v-if="shopActivityList[presentsIndex]">
                                <template v-if="shopActivityList[presentsIndex].description">
                                    <span class="tit-txt">{{ shopActivityList[presentsIndex].description }}</span>
                                </template>
                            </template>
                        </div>
                        <div class="item-con">
                            <template v-if="shopActivityList[presentsIndex]">
                                <template v-if="shopActivityList[presentsIndex].presents">
                                    <div
                                        class="gifts"
                                        v-for="(presentItem, presentIndex) in shopActivityList[presentsIndex].presents"
                                        :key="presentIndex"
                                    >
                                        <span class="gifts-img"><img :src="$imgUrlHead + presentItem.pic" alt="" /></span>
                                        <span class="gifts-txt">{{ presentItem.name }}</span>
                                    </div>
                                </template>
                            </template>
                        </div>
                    </div>
                </div>
                <button class="popup-btn" @click="closeAll" :style="{ background: themes.color }">我知道了</button>
            </div>
        </div>
        <!-- /促销信息 -->

        <!-- 跨境相关 -->
        <van-action-sheet v-model="haitaoFlag" title="请分开结算以下商品" :round="false">
            <div class="hai-content cart cart-list" :class="themes.theme">
                <div
                    class="item"
                    v-for="(item, index) in goodsTypeCartItems"
                    :key="index"
                    :style="{ 'padding-bottom': index == 0 ? '10px' : '15px' }"
                    @click="switchGoods(item, index)"
                >
                    <em class="choose" :class="{ cur: item.flag }"></em>
                    <span class="name" v-if="item.type == 'overseas'">
                        <span class="dtrangle">跨境</span>
                        跨境商品 {{ item.ids.length }}件
                    </span>
                    <span class="name" v-if="item.type == 'normal'">普通商品 {{ item.ids.length }} 件</span>
                </div>
                <div class="Buytype">
                    <div class="popup-btn first-btn" @click="haitaoFlag = false">返回购物车</div>
                    <div class="popup-btn" @click="confirmSettlement">确认结算</div>
                </div>
            </div>
        </van-action-sheet>
        <!-- 跨境相关 -->
    </div>
</template>

<script>
import {
    shopCart,
    changeBasketSts,
    batchChgBasketSts,
    selectSkus,
    deleteShopCart,
    deleteShopCarts,
    changeShopCartNum,
    clearInvalid,
    changeSelectedSku,
    cartCount
} from 'api/cart'
import { favoriteGoodsDels } from 'api/collectManage'
import legendImage from 'components/legendImage/legendImage'
import copyrightInfo from 'components/copyrightInfo/copyrightInfo'
import { SwipeCell, CellGroup } from 'vant'
import sendTo from '../../views/goodsDetail/components/sendTo'
import cash from 'utils/tool'
import StringUtils from 'utils/stringUtils.js'
import { debounce } from 'utils/utils.js'
import { mapState } from 'vuex'
export default {
	name: 'cart',
    data() {
        return {
            //
            themesColor: 'themes.color',
            borderTop: 'border-top: none',
            haitaoFlag: false,
            shopList: [], //有效列表
            shopActivityList: [], //有效的参加活动列表
            presentsIndex: 0,
            paramData: '', //规格列表
            result: '', //获取到的所有数据
            invalidCartItems: [], //无效列表
            Money: cash, //价格转换
            allChecked: 0, //全部选择
            promotionPrice: 0, //sku价格
            skuImages: 0, //sku图片
            prodName: '', //skuName当前的名字
            param: '', //多选的一个对象(全选)
            changeStr: [], //多选的对象集合（全选）
            shop: '', //多选的一个对象(店铺)
            shops: [], //多选的对象集合（店铺）
            favoriteGoods: [], //批量收藏的数据集合
            deleteGoods: '', //批量删除的数据集合
            showSkuList: false, //展示skulist
            onActive: {}, //被选中的sku
            oldOnActive: {}, //默认被选中的sku
            onActiveName: {}, //被选中的sku名字
            oldOnActiveName: {}, //默认被选中的sku名字
            propName: [], //名字
            prodPropList: '', //商品属性集合
            goodsPic: '', //弹出层图片
            goodsNum: 1, //sku购买数量
            price: 1, //各个sku下商品的原价
            cash: 1, //各个sku下商品的现价
            skuList: 1, //skulist
            goodsDetailData: '', //商品sku详情
            showEdit: false, //商品sku详情
            prodCount: 1, //更改的sku的默认数量
            basketId: 1, //更改的sku的basketId
            oldSkuId: 1, //更改的sku的原sku
            prodId: 1, //更改的sku的原sku
            checkedGoods: '', //被选中的商品的sku集合
            checkedGoodsNum: 0, //被选中的商品数量
            checkedGoodsPrice: 0, //被选中的商品价格
            showActivity: false,
            discount: 0, //是否有折扣。 默认0是没有折扣
            joinDiscount: false, //是否是限时折扣
            goodsTypeCartItems: [],
            addrData: {
                type: 0, //0:选择用户已有的收货地址(后台读取addrId数据)，1：自定义选择区域(后台读取addrList数据)
                addrId: '',
                addrList: [],
                addrName: ''
            },
            stocks: null, //购物车数量
			isPurchase: true, //判断商品是否可购买
			startSaleFlagArr: [] //flag属性值值都为true禁用结算按钮
        }
    },
    activated() {
        let that = this
        //买家在商品详情页面选择的收货地址要缓存到本地, 进入下一个商品时就从本地获取收货地址来请求商品详情接口
        // if (!StringUtils.isEmpty(sessionStorage.getItem('addrData'))) {
        //     this.addrData = JSON.parse(sessionStorage.getItem('addrData'))
        // }
        this.init()
    },
    mounted() {
        // 进入商品详情时，清除订单中缓存的路由信息
        sessionStorage.removeItem('preRoute')
    },
    methods: {
        //初始化整个页面数据
        init() {
            shopCart({
                type: this.addrData.type ? this.addrData.type : 0,
                addrId: this.addrData.addrId ? this.addrData.addrId : '',
                addrList: this.addrData.addrList ? this.addrData.addrList : [],
                addrName: this.addrData.addrName ? this.addrData.addrName : ''
            }).then((res) => {
                if (res.status == 1) {
                    if (res.result) {
                        this.result = res.result
                        this.shopList = res.result.enableCartList ? res.result.enableCartList : [] // 非活动商品start
                        this.shopActivityList = res.result.promotionCartList ? res.result.promotionCartList : [] //活动
                        this.invalidCartItems = res.result.disableCartList ? res.result.disableCartList : [] //失效商品
                        this.checkAll()

                        if (!StringUtils.isEmpty(res.result.addrData)) {
                            this.addrData = res.result.addrData //值传到后台后，后台再原封不动的返回给前端(当前端不传值时，则返回的是默认地址或北京朝阳区)
                            // sessionStorage.setItem('addrData', JSON.stringify(this.addrData)) //买家在商品详情页面选择的收货地址要缓存到本地, 进入下一个商品时就从本地获取收货地址来请求商品详情接口.
							sessionStorage.setItem('addrId', this.addrData.addrId || '')
                        }

                        // this.getCartCount()
                    } else {
                        this.result = res.result
                        // this.getCartCount()
                    }
                }
            })
        },
        goback() {
            this.$router.back()
            this.$router.isBack = true
        },
        //购物车角标
        getCartCount() {
            cartCount().then((res) => {
                if (res.status == 1) {
                    this.$store.state.cartNum = res.result
                }
            })
        },
        //门店自提 暂时屏蔽
        //  goStoreSub(shopIndex) {
        //    let changeStr = [];
        //    let param;
        //    let that = this
        //    let oneshopNum = 0
        //    let trueNum = 0
        //    for(let j = 0 ; j< this.shopList[shopIndex].groupCartItems.length ; j++) {      //for商家的分类数量
        //      if(this.shopList[shopIndex].groupCartItems[j].cartItems && this.shopList[shopIndex].groupCartItems[j].cartItems.length != 0) {
        //        oneshopNum = oneshopNum + this.shopList[shopIndex].groupCartItems[j].cartItems.length
        //        for(let k = 0 ; k< this.shopList[shopIndex].groupCartItems[j].cartItems.length ; k++) {     //for商家的每个分类的商品
        //          if(this.shopList[shopIndex].groupCartItems[j].cartItems[k].checkSts == 1 && this.shopList[shopIndex].groupCartItems[j].cartItems[k].supportStore) {
        //            changeStr.push(this.shopList[shopIndex].groupCartItems[j].cartItems[k].basketId)
        //          }
        //        }
        //      }
        //    }
        //    var orderIfo = {
        //      shopCartItems:changeStr,
        //      buyNow: false,
        //      shopId: this.shopList[shopIndex].shopId
        //    }
        //    sessionStorage.setItem("storeIfo",JSON.stringify(orderIfo))
        //    if(changeStr && changeStr.length) {
        //      this.$router.push('/storeSubmit')
        //    }else {
        //      this.$toast("该商品不支持门店自提服务")
        //    }
        //  },
        //检查是否全选(店铺跟所有商品)
        checkAll(checked, shopIndex) {
            this.checkedGoods = ''
            this.checkedGoodsNum = 0
            this.checkedGoodsPrice = 0
            let checkedShop = 0
            let checkedGoodsArr = []
			this.startSaleFlagArr = []
            let allGood = 0 //商品的数量
            if (this.shopList && this.shopList.length != 0) {
                for (let i = 0; i < this.shopList.length; i++) {
                    //for不参加活动的商品
                    //start所有全选
                    this.param = JSON.stringify({
                        key: this.shopList[i].basketId,
                        value: +checked
                    })
                    this.changeStr.push(this.param)
                    //end所有全选
                    allGood = allGood + 1
                    if (this.shopList[i].checkSts) {
						this.startSaleFlagArr.push({
							'flag': this.shopList[i].startSaleFlag,
							'item': this.shopList[i]
						});
                        //是否全选
                        if (this.checkedGoods) {
                            this.checkedGoods = this.checkedGoods + ',' + this.shopList[i].basketId
                        } else {
                            this.checkedGoods = this.checkedGoods + '' + this.shopList[i].basketId
                        }
                        this.checkedGoodsNum = this.checkedGoodsNum + 1
                    }
                }
            }
            if (this.shopActivityList) {
                for (let i = 0; i < this.shopActivityList.length; i++) {
                    //for参加活动的商品
                    for (let j = 0; j < this.shopActivityList[i].hitCartItems.length; j++) {
                        //start所有全选
                        this.param = JSON.stringify({
                            key: this.shopActivityList[i].hitCartItems[j].basketId,
                            value: +checked
                        })
                        this.changeStr.push(this.param)
                        //end所有全选
                        allGood = allGood + 1
                        if (this.shopActivityList[i].hitCartItems[j].checkSts) {
							this.startSaleFlagArr.push({
								'flag': this.shopActivityList[i].hitCartItems[j].startSaleFlag,
								'item': this.shopActivityList[i].hitCartItems[j]
							});
                            //是否全选
                            if (this.checkedGoods) {
                                this.checkedGoods = this.checkedGoods + ',' + this.shopActivityList[i].hitCartItems[j].basketId
                            } else {
                                this.checkedGoods = this.checkedGoods + '' + this.shopActivityList[i].hitCartItems[j].basketId
                            }
                            this.checkedGoodsNum = this.checkedGoodsNum + 1
                        }
                    }
                }
            }
			if(this.startSaleFlagArr.findIndex(item => item.flag == false) === -1 ) {
				this.isPurchase = false
			}else {
				this.isPurchase = true
			}
			
            this.checkedGoods.substr(1, 1)
            if (this.checkedGoodsNum == allGood) {
                this.allChecked = 1
            } else {
                this.allChecked = 0
            }
        },
        //跳转到店铺
        goShop(shopId) {
            this.$router.push({
                path: `/shopIndex`,
                query: {
                    shopId: shopId
                }
            })
        },
		//延迟修改商品选中状态 防抖
		changeDebounce:debounce(function(params) {
			changeBasketSts(params).then((res) => {
			    this.init()
			})
		}),
        //更改购物车选中状态(单选)
        changeBasketSts(basketId, checkSts, activityType, typeIndex, goodIndex) {
            if (checkSts == 1) {
                checkSts = 0
                if (activityType == 'on') {
                    this.shopActivityList[typeIndex].hitCartItems[goodIndex].checkSts = 0
                } else {
                    this.shopList[typeIndex].checkSts = 0
                }
            } else {
                checkSts = 1
                if (activityType == 'on') {
                    this.shopActivityList[typeIndex].hitCartItems[goodIndex].checkSts = 1
                } else {
                    this.shopList[typeIndex].checkSts = 1
                }
            }
            // this.checkAll()
			let params = { basketId: basketId, checkSts: checkSts }
			// debounce(this.changeDebounce, 1000, params)()
			this.changeDebounce(params)
        },
        //跳转到优惠券中心
        goRecCenter() {
            this.$router.push('/walletModules/recCenter/recCenter')
        },
        //改变所有商品选中状态(全选)
        changeAllShop() {
            this.changeStr = []
            this.param
            if (this.allChecked == 1) {
                this.allChecked = 0
            } else {
                this.allChecked = 1
            }
            this.checkAll(this.allChecked)
            let changeStr = this.changeStr
            batchChgBasketSts({ entities: '[' + changeStr + ']' }).then((res) => {
                this.init()
            })
        },
        //改变单个店铺选择(多选)
        changeOneShop(shopIndex, checked) {
            this.shops = []
            this.shop
            if (checked == 1) {
                checked = 0
                this.shopList[shopIndex].checked = 0
            } else {
                checked = 1
                this.shopList[shopIndex].checked = 1
            }
            this.checkAll(checked, shopIndex)
            let changeStr = this.shops
            batchChgBasketSts({ changeStr: '[' + changeStr + ']' }).then((res) => {
                this.init()
            })
        },
        //批量添加收藏
        favoriteSomeGoodsDels() {
            this.favoriteGoods = ''
            this.checkAll()
            this.favoriteGoods = this.favoriteGoods.substr(1)
            favoriteGoodsDels({ selectedProdId: this.favoriteGoods }).then((res) => {
                if (res.status == 1) {
                    this.$toast('已添加收藏')
                }
            })
        },
        //关闭所有弹框
        closeAll() {
            this.showSkuList = false
            this.showActivity = false
        },
        //跳转到商品详情
        goDoodsDetail(prodId) {
            this.$router.push({
                path: `/goodsDetail`,
                query: {
                    goodsInfoId: prodId
                }
            })
        },
        //初始化sku
        selectSkus(prodId, skuId, basketCount, basketId) {
            this.showSkuList = true
            selectSkus({ prodId: prodId }).then((res) => {
                this.goodsDetailData = res.result
                this.skuList = res.result
                this.basketId = basketId
                this.prodCount = basketCount //默认的basketId
                this.oldSkuId = skuId //默认的skuId
                this.skuId = skuId //默认的skuId
                this.prodId = prodId //prodId
                let aaa
                this.onActive = []
                this.oldOnActive = []
                this.onActiveName = []
                this.oldOnActiveName = []
                let showData = []
                let paramData = []
                let defaultAttr
                if (this.skuList[0].cnProperties) {
                    let keyArr = this.skuList[0].cnProperties.split(';')
                    for (let i = 0; i < keyArr.length; i++) {
                        const element = keyArr[i]
                        showData.push({
                            key: element.split(':')[0],
                            attrArr: []
                        })
                        paramData.push({
                            key: element.split(':')[0],
                            attrArr: []
                        })
                    }
                    for (let j = 0; j < this.skuList.length; j++) {
                        let arr = this.skuList[j].cnProperties.split(';')

                        if (this.skuList[j].skuId == skuId) {
                            defaultAttr = this.skuList[j].cnProperties

                            this.skuId = this.skuList[j].skuId
                            this.stocks = this.skuList[j].stocks || 0
                            this.prodName = this.skuList[j].name
                            this.skuImages = this.skuList[j].pic ? this.skuList[j].pic : ''
                            this.skuBanner = this.skuList[j].images
                            this.discount = this.skuList[j].discount
                            this.joinDiscount = this.skuList[j].joinDiscount


                            if (this.skuList[j].promotionPrice) {
                                this.price = this.skuList[j].price
                                this.promotionPrice = this.skuList[j].promotionPrice
                            } else {
                                this.promotionPrice = this.skuList[j].price
                            }
                        }

                        for (let index = 0; index < arr.length; index++) {
                            showData[index].attrArr.push(arr[index].split(':')[1])
                        }
                    }
                    for (let i = 0; i < showData.length; i++) {
                        showData[i].attrArr.sort()
                        for (let j = 0; j < showData[i].attrArr.length; j++) {
                            if (showData[i].attrArr[j] != showData[i].attrArr[j + 1]) {
                                paramData[i].attrArr.push({
                                    choose: 'default',
                                    value: showData[i].attrArr[j]
                                })
                            }
                        }
                    }
                    this.paramData = paramData
                    let obj = {}

                    for (let i = 0; i < paramData.length; i++) {
                        let str = paramData[i].key
                        obj[str] = defaultAttr.split(';')[i].split(':')[1]
                    }
                    this.onActive = obj
                    let choosedArr = []

                    for (const key in this.onActive) {
                        choosedArr.push(key + ':' + this.onActive[key])
                        for (let i = 0; i < this.paramData.length; i++) {
                            for (let j = 0; j < this.paramData[i].attrArr.length; j++) {
                                if (this.onActive[key] == this.paramData[i].attrArr[j].value) {
                                    this.paramData[i].attrArr[j].choose = 'on'
                                }
                            }
                        }
                    }

                    this.choosedText = !defaultAttr ? '' : choosedArr
                } else {
                    this.skuId = this.skuList[0].skuId
                    this.stocks = this.skuList[0].stocks || 0
                    this.prodName = this.skuList[0].name
                    this.skuImages = this.skuList[0].pic ? this.skuList[0].pic : ''
                    this.skuBanner = this.skuList[0].images
                    if (this.skuList[0].promotionPrice) {
                        this.price = this.skuList[0].price
                        this.promotionPrice = this.skuList[0].promotionPrice
                    } else {
                        this.promotionPrice = this.skuList[0].price
                    }
                }
            })
        },
        //选择sku
        currentFilter(prodPropValIndex, prodPropIndex, key, value) {
            let arrIndex = prodPropIndex //外层for选中的index
            let valueIndex = prodPropValIndex //当前选中的index
            let key1 = key //当前选中的key
            let attr = value


            for (let index = 0; index < this.paramData[arrIndex].attrArr.length; index++) {
                this.paramData[arrIndex].attrArr[index].choose = 'defalut'
                this.paramData[arrIndex].attrArr[valueIndex].choose = 'on'
            }

            let combo = key1 + ':' + attr
            const currentId = []

            for (let i = 0; i < this.skuList.length; i++) {
                let elemt = this.skuList[i]
                if (elemt['cnProperties'].indexOf(combo) > -1 && elemt['status'] > 0 && elemt['stocks'] > 0) {
                    const tmp = elemt['cnProperties'].split(';')
                    tmp.splice(tmp.indexOf(combo), 1)
                    for (let j = 0; j < tmp.length; j++) {
                        currentId.push(tmp[j].split(':')[1]) //切分出来的是可组合的valueId
                    }
                }
            }

            for (let index = 0; index < this.paramData.length; index++) {
                const element = this.paramData[index]
                if (element.key !== key1) {
                    for (let j = 0; j < element.attrArr.length; j++) {
                        if (currentId.indexOf(element.attrArr[j].value.toString()) === -1) {
                            element.attrArr[j]['disable'] = true //如果没有合适的，则设为不可选
                        } else {
                            element.attrArr[j]['disable'] = false //否则设为可选
                        }
                    }
                }
            }
            this.onActive[key1] = attr
            let check = false
            let skuArr = [] //把所有拆分项放入数组里
            for (let key in this.onActive) {
                skuArr.push(key + ':' + this.onActive[key])
            }
            if (skuArr.length == 0) {
                skuArr.push(this.goodsDetArr.name)
            }
            this.choosedText = skuArr

            for (let i = 0; i < this.skuList.length; i++) {
                for (let index = 0; index < skuArr.length; index++) {
                    if (this.skuList[i].cnProperties.indexOf(skuArr[index]) != -1) {
                        check = true //假设j=1的循环结束以后还保持check=true的状态
                    } else {
                        check = false
                        break
                    }
                }

                if (check === true) {
                    this.skuId = this.skuList[i].skuId
                    this.promotionPrice = this.skuList[i].promotionPrice
                    this.stocks = this.skuList[i].stocks || 0
                    this.prodName = this.skuList[i].name
                    this.skuImages = this.skuList[i].pic ? this.skuList[i].pic : this.goodsDetArr.pic
                    this.skuBanner = this.skuList[i]
                    this.discount = this.skuList[i].discount
                    this.joinDiscount = this.skuList[i].joinDiscount

                    if (this.skuList[i].promotionPrice) {
                        this.promotionPrice = this.skuList[i].promotionPrice
                    } else {
                        this.promotionPrice = this.skuList[i].price
                        this.prodName = this.skuList[i].name
                    }
                }
            }
        },
        //删除购物车商品
        onClose(basketId, proId, skuId) {
            this.$dialog
                .confirm({
                    message: '是否从购物车删除该商品'
                })
                .then(() => {
                    deleteShopCart({ basketId: basketId, prodId: proId, skuId: skuId }).then((res) => {
                        if (res.status == 1) {
                            this.init()
                        } else {
                            this.$toast(res.msg)
                        }
                    })
                })
                .catch(() => {
                    // on cancel
                })
        },
        //批量删除购物车商品
        deleteShopCarts() {
            if (this.checkedGoods) {
                this.$dialog
                    .confirm({
                        message: '是否将选中商品从购物车删除'
                    })
                    .then(() => {
                        this.deleteGoods = this.checkedGoods
                        deleteShopCarts({ baskeIds: this.deleteGoods }).then((res) => {
                            if (res.status == 1) {
                                this.init()
                            } else {
                                this.$toast(res.msg)
                            }
                        })
                    })
                    .catch(() => {
                        // on cancel
                    })
            } else {
                this.$toast('请选择删除的商品')
            }
        },
        //更改购物车数量
        numChange(num, basketCount, prodId, skiId, index, basketId) {
            if (num == -1) {
                if (basketCount - 1 > 0) {
                    basketCount = basketCount - 1
                } else {
                    this.$toast('购买的数量不能小于1')
                }
            } else if (num == 1) {
                basketCount = basketCount + 1
            }
            changeShopCartNum({
                count: basketCount,
                prodId: prodId,
                skuId: skiId,
                basketId: basketId,
                address: this.addrData.addrName.replace(/\s*/g, '')
            }).then((res) => {
                if (res.status == 1) {
                    this.init()
                } else {
                    this.$toast(res.msg)
                }
            })
        },
        //手动更改购物车数量
        manualChangeCount(basketCount, prodId, skuId, index, stocks, basketId) {

            if (basketCount <= 0) {
                this.$toast('购买数量不能低于1')
                this.init()
                event.preventDefault()
            } else {
                if (basketCount <= stocks) {
                    changeShopCartNum({
                        count: parseInt(basketCount),
                        prodId: prodId,
                        skuId: skuId,
                        basketId,
                        address: this.addrData.addrName.replace(/\s*/g, '')
                    }).then((res) => {
                        if (res.status == 1) {
                            this.init()
                        } else {
                            this.$toast(res.msg)
                            event.preventDefault()
                            this.init()
                        }
                    })
                } else {
                    this.$toast('库存不足')
                    this.init()
                }
            }
        },
        //清空购物车失效商品
        clearInvalid() {
            this.$dialog
                .confirm({
                    message: '是否清空购物车失效商品'
                })
                .then(() => {
                    let param
                    let changeStr
                    for (var i = 0; i < this.invalidCartItems.length; i++) {
                        param = this.invalidCartItems[i].basketId
                        changeStr = changeStr + ',' + param
                    }
                    changeStr = changeStr.substr(10)
                    deleteShopCarts({ baskeIds: changeStr }).then((res) => {
                        if (res.status == 1) {
                            this.init()
                        } else {
                            this.$toast(res.msg)
                        }
                    })
                })
                .catch(() => {
                    // on cancel
                })
        },
        //结算购物车选中的商品
        settlement() {
            // 判断所选商品的配送方式是否一致
            if (this.result.hasNotDeliveryType) {
                this.$toast('所选商品的配送方式不一致~')
                return
            }
			
			//判断是否禁用结算按钮
			if(!this.isPurchase) {
				let title = this.startSaleFlagArr.length == 1 ?`该商品限购${this.startSaleFlagArr[0].item.purchaseLimitAmount}件`:`商品剩余可购数量不足，请校验数量后提交`;
				// let title = this.startSaleFlagArr.length == 1 ?`该商品限购`:`商品剩余可购数量不足，请校验数量后提交`;
				this.$toast(title)
				return
			}
			
            let changeStr = []
            let goodsTypeCartItems = [] //存放
						
            if (this.shopList) {
                this.shopList.map((v) => {
                    let map = {}
                    if (v.checkSts) {
                        changeStr.push(v.basketId)
                        map = {
                            basketId: v.basketId,
                            goodsType: v.goodsType
                        }
                        goodsTypeCartItems.push(map)
                    }
                })
            }

            if (this.shopActivityList) {
                this.shopActivityList.map((v, index) => {
                    let map = {}
                    v.hitCartItems.map((cartIteme, cartIindex) => {
                        if (cartIteme.checkSts) {
                            changeStr.push(cartIteme.basketId)
                            map = {
                                basketId: cartIteme.basketId,
                                goodsType: cartIteme.goodsType
                            }
                            goodsTypeCartItems.push(map)
                        }
                    })
                })
            }


            let haitaoCount = 0 //跨境的数量
            let normalCount = 0 // 不是跨境的数量
            goodsTypeCartItems.forEach((item) => {
                item.goodsType == 'overseas' && haitaoCount++
                item.goodsType == 'normal' && normalCount++
            })

            let isAll = haitaoCount > 0 && normalCount > 0

            if (isAll) {
                this.haitaoFlag = true
                let config = {
                    overseas: 0,
                    normal: 1
                }

                let goodsTypeCarArr = goodsTypeCartItems.reduce((res, item) => {
                    let obj = res[config[item.goodsType]]
                    if (!obj) {
                        obj = {
                            array: [],
                            flag: item.goodsType == 'overseas',
                            type: item.goodsType,
                            ids: []
                        }
                    }
                    obj.array.push(item)
                    obj.ids.push(item.basketId)
                    res[config[item.goodsType]] = obj
                    return res
                }, [])

                this.goodsTypeCartItems = goodsTypeCarArr
                return
            }
            if (changeStr && changeStr.length) {
                this.$router.push({
                    path: `/submitOrder`,
                    query: {
                        shopCartItems: changeStr,
                        type: 'NORMAL',
                        buyNow: false
                    }
                })
            } else {
                this.$toast('亲,请选择您要结算的商品!')
            }
        },

        //切换跨境or普通商品
        switchGoods(item, index) {
            this.goodsTypeCartItems.map((item) => {
                item.flag = false
            })
            item.flag = true
        },

        confirmSettlement() {
            this.goodsTypeCartItems.find((v) => v.flag == true)
            this.$router.push({
                path: `/submitOrder`,
                query: {
                    shopCartItems: this.goodsTypeCartItems.find((v) => v.flag == true).ids,
                    type: 'NORMAL',
                    buyNow: false
                }
            })
        },

        //更改sku时更改其数量
        changeSpuCount(num, prodCount) {
            if (num == -1) {
                if (this.prodCount - 1 > 0) {
                    this.prodCount = this.prodCount - 1
                } else {
                    this.$toast('购买的数量不能小于1')
                }
            } else if (num == 1) {
                this.prodCount = this.prodCount + 1
            }
        },
        //更改购物车商品的sku
        changeSelectedSku() {
            changeSelectedSku({
                count: this.prodCount,
                basketId: this.basketId,
                oldSkuId: this.oldSkuId,
                prodId: this.prodId,
                newSkuId: this.skuId
            }).then((res) => {
                if (res.status == 1) {
                    this.init()
                    this.showSkuList = false
                } else {
                    this.$toast(res.msg)
                }
            })
        },
        //失效商品重新选择
        reChecked(prodId) {
            this.$router.push({
                path: `/goodsDetail`,
                query: {
                    goodsInfoId: prodId
                }
            })
        },
        //跳转首页
        goIndex() {
            this.$router.push({
                path: `/index`
            })
        },
        showPresents(index) {
            this.showActivity = true
            this.presentsIndex = index
        },

        // 点击"送至"里的地址
        choiceAdd(addrId) {
            this.addrData = {
                type: 0, //0:选择用户已有的收货地址(后台读取addrId数据)，1：自定义选择区域(后台读取addrList数据)
                addrId: addrId,
                addrList: [],
                addrName: ''
            }
            this.init()
        },

        onAddress(addrData) {
            this.addrData = addrData
            this.init()
        }
    },
    deactivated() {
        this.showEdit = false
    },
    computed: {
        ...mapState(['themes'])
    },
    components: {
        SwipeCell,
        CellGroup,
        legendImage,
        copyrightInfo,
        sendTo
    }
}
</script>

<style src="@/assets/css/style/cart-style.css" scoped></style>
<style src="@/assets/css/style/popup-style.css" scoped></style>
<style src="@/assets/css/style/detail-style.css" scoped></style>
<style src="@/assets/css/cart.css" scoped></style>
<style src="@/assets/css/empty.css" scoped></style>
<style src="@/assets/css/detail.css" scoped></style>
<style src="@/assets/css/popup.css" scoped></style>
<style scoped>
.del-goods {
    width: 75px;
    height: 90px;
    text-align: center;
    line-height: 90px;
    font-size: 14px;
    color: #ffffff;
    margin: 13px 0 0 25px;
    margin-right: -85px;
}
.item.pointerEvents {
    pointer-events: none;
}
</style>
<style>
.van-swipe-cell__right {
    /* background: #4eae31!important; */
    width: 77px !important;
    height: 100% !important;
    line-height: 107px !important;
    font-size: 14px !important;
    color: #ffffff !important;
    margin: 0px 0 0 20px !important;
    margin-right: -15px !important;
}
.cart.green .van-swipe-cell__right {
    background: #4eae31 !important;
}
.cart.crimson .van-swipe-cell__right {
    background: #de0233 !important;
}
.cart.red .van-swipe-cell__right {
    background: #e5004f !important;
}
.cart.pale-red .van-swipe-cell__right {
    background: #fd8cb0 !important;
}
.cart.orange .van-swipe-cell__right {
    background: #ff6700 !important;
}
.cart.brown .van-swipe-cell__right {
    background: #bc9f5f !important;
}
.cart.blue .van-swipe-cell__right {
    background-color: #2e82e3 !important;
}
.cart.light-green .van-swipe-cell__right {
    background-color: #5fc221 !important;
}
.cart.black .van-swipe-cell__right {
    background-color: #5fc221 !important;
}
/*消除vant的hidden*/
.van-swipe-cell {
    overflow: visible !important;
}
.cart {
    overflow-x: hidden;
}
.van-hairline--top-bottom::after {
    border-width: 0;
}
.cart .cart-list .cart-con .promotion-goods .promotion-item .check img {
    width: 8px;
    height: 8px;
    vertical-align: middle;
    margin-top: -2px;
    display: inline-block;
}

.cart .cart-btn .right.disabled {
    background: rgba(204, 204, 204, 1) !important;
}
</style>
